package com.zdxk.msgPush.dataAxis.job;

import com.zdxk.msgPush.common.config.ServiceConfig;
import com.zdxk.msgPush.stockMsg.read.service.StockDataReadService;
import org.apache.rocketmq.client.exception.MQBrokerException;
import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.remoting.exception.RemotingException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;

@Component
public class DateAxisJob {

    private static Logger logger = LoggerFactory.getLogger(DateAxisJob.class);

    @Autowired
    private StockDataReadService stockDataReadService;

    private Calendar date;

    @Scheduled(cron = "* * * * * *")
    public void getStockTradeData(){
        if(date == null){
            try {
                date = getStockEarliestDate();
            } catch (ParseException e) {
                logger.error("发布{}的消息失败",e);
            }
        }else{
            date.add(Calendar.DATE,1);
        }
        try {
            stockDataReadService.publishAllStockTradeByDate(date);
        } catch (IOException|InterruptedException|RemotingException|MQClientException|MQBrokerException e) {
            logger.error("生产者发布消息到rocketMq失败",e);
        }

    }

    private Calendar getStockEarliestDate() throws ParseException {
        String tradeStartDateStr = ServiceConfig.getConf("stock.trade.startData");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        Calendar tradeCalendar = Calendar.getInstance();
        tradeCalendar.setTime(sdf.parse(tradeStartDateStr));
        return tradeCalendar;
    }
}
